import { Injectable } from '@nestjs/common';
import { merge } from 'lodash';

import * as sanitizeHtml from 'sanitize-html';

@Injectable()
export class SanitizeService {
    // protected修饰符是只允许在当前类内部和当前类的子类可以访问
    protected config: sanitizeHtml.IOptions = {};

    constructor() {
        this.config = {
            allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'code']),
            allowedAttributes: {
                ...sanitizeHtml.defaults.allowedAttributes,
                '*': ['style', 'class', 'width', 'height'],
            },
            parser: {
                lowerCaseTags: true,
            },
        };
    }

    sanitize(body: string, options?: sanitizeHtml.IOptions) {
        return sanitizeHtml(
            body,
            merge(this.config, options ?? {}, {
                arrayMerge: (_d, s, _o) => s,
            }),
        );
    }
}
